package org.example.order;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 *    调用打印机的方法
 */

public class PrintUtil {

    public static void main(String[] args) {
        print(new ArrayList<>());
    }

    public static void print(List<PrintOrder> orderList){
        PrintOrder printOrder = new PrintOrder();
        printOrder.setId(204433307096715264L);
        printOrder.setOrderId(204130596568567808L);
        printOrder.setWayBillNo("17LE-WL-020113264676");
        printOrder.setSelfPickUpName("阳光超市西湖店大门口");
        printOrder.setSelfPickUpNo("0003");
        printOrder.setUserName("王*");
        printOrder.setUserPhone("138****1234");
        printOrder.setUserAddress("山西省运城市盐湖区河东东街333号");

        List<String> orderProductNames =new ArrayList<>();
        orderProductNames.add("迷你折叠露营车 *1");
        orderProductNames.add("iphone16 银白色 256G proMax *15");
        orderProductNames.add("金丝楠木床 1.8*2 *2");
        orderProductNames.add("小米全智能空调 省电 高效 好 5匹 一级能耗 *2");
        orderProductNames.add("蓝色妖姬 收藏款 蓝色 20支 中支烟 整条*6");
        orderProductNames.add("minibulu *1");

        printOrder.setOrderDetailList(orderProductNames);

        printOrder.setOrderProductCount(16);
        orderList.add(printOrder);

        String printerName = "HPRT N31C";
        for (PrintOrder order : orderList) {
            connectPrint(order,printerName);
        }
    }

    public static void connectPrint(PrintOrder order,String printerName){
        byte[] bytes;
        try {
           System.out.println("生成pdf流");
           bytes = CreatePdfUtil.savePdf(order);
           System.out.println("生成pdf流完成");

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        try (PDDocument document =  Loader.loadPDF(bytes);) {
            // 查找打印机
            PrintService printer = findPrinter(printerName);
            if (printer == null) {
                System.out.println("未找到打印机: " + printerName);
                return;
            }

            // 创建打印作业
            PrinterJob job = PrinterJob.getPrinterJob();
            job.setPrintService(printer);
            job.setPageable(new PDFPageable(document));

            // 执行打印
            job.print();
            System.out.println("PDF 打印任务已提交");

        } catch (Exception e) {
            System.err.println("打印失败: ");
            e.printStackTrace();
        }


    }


    private static PrintService findPrinter(String name) {
        for (PrintService service : PrintServiceLookup.lookupPrintServices(null, null)) {
            if (service.getName().equalsIgnoreCase(name)) {
                return service;
            }
        }
        return null;
    }
}
